package com.wyk.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.CRC32;

/**
 * @author WangYuKai
 * @Date 2022/6/22
 * @apiNote
 */
@Component
public class MyLB implements LoadBlancer{

    private AtomicInteger atomicInteger = new AtomicInteger(0);
    //得到下标并增加
    public final int getAndincrement(){
        int current;
        int next;
        do{
            current = this.atomicInteger.get();
            next = current >= 2147483647 ? 0 : current + 1;
        }while (! this.atomicInteger.compareAndSet(current,next));
        System.out.println("**第几次访问：次数**next" + next);
        return next;
    }
    @Override
    public ServiceInstance instance(List<ServiceInstance> servers) {
        //取余(用来获取下标)
        int index = getAndincrement() % servers.size();

        return servers.get(index);
    }
}
